﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Ekton_Manage_Framework.Methods.HttpSender
{
    public class HttpRequestMethod
    {

        private static HttpClient client = new HttpClient();
        private readonly HttpSenderHelper _httpSender;
        public HttpRequestMethod(HttpSenderHelper httpSender)
        {
            _httpSender = httpSender;
        }
        public async Task<string> Get(string url)
        {
            Task<HttpResponseMessage> async = client.GetAsync(url);
            try
            {
                return await _httpSender.RunTask(async);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public async Task<string> Get(string Url, string postDataStr, string id, string token)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.Timeout = 10 * 1000;//设置10s的超时
            request.ContentType = "text/html;charset=UTF-8";
            request.Headers.Add("id", id);
            request.Headers.Add("access_token", token);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        public async Task<string> Delete(string url)
        {
            url = await _httpSender.FixUrl(url);
            Task<HttpResponseMessage> task = client.DeleteAsync(url);
            try
            {
                return await _httpSender.RunTask(task);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public async Task<string> Post(string url, string content)
        {
            url = await _httpSender.FixUrl(url);
            HttpContent streamContent = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(content)));
            //streamContent.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            streamContent.Headers.Add("Content-Type", "application/json");
            //streamContent.Headers.Add("Content-Type", "text/html;charset=UTF-8");
            //streamContent.Headers.Add("id", id);
            //streamContent.Headers.Add("Authorization", token);

            Task<HttpResponseMessage> task = client.PostAsync(url, streamContent);
            try
            {
                return await _httpSender.RunTask(task);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 发送POST请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="data">请求参数</param>
        /// <returns></returns>
        public async Task<string> Post(string url, string data, string token)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            //字符串转换为字节码
            byte[] bs = Encoding.UTF8.GetBytes(data);
            //参数类型，这里是json类型
            //还有别的类型如"application/x-www-form-urlencoded"
            httpWebRequest.ContentType = "application/json";
            //参数数据长度
            httpWebRequest.ContentLength = bs.Length;
            //设置请求类型
            httpWebRequest.Method = "POST";
            //设置超时时间
            httpWebRequest.Timeout = 20000;
            //将参数写入请求地址中
            httpWebRequest.GetRequestStream().Write(bs, 0, bs.Length);
            //请求头加入token
            httpWebRequest.Headers.Add("Authorization", token);
            //发送请求
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //读取返回数据
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
            string responseContent = streamReader.ReadToEnd();
            streamReader.Close();
            httpWebResponse.Close();
            httpWebRequest.Abort();
            return responseContent;
        }

        /// <summary>
        /// 发送PUT请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="data">请求参数</param>
        /// <returns></returns>
        /// 
        public async Task<string> Put(string url, string data, string token)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            //字符串转换为字节码
            byte[] bs = Encoding.UTF8.GetBytes(data);
            //参数类型，这里是json类型
            //还有别的类型如"application/x-www-form-urlencoded"
            httpWebRequest.ContentType = "application/json";
            //参数数据长度
            httpWebRequest.ContentLength = bs.Length;
            //设置请求类型
            httpWebRequest.Method = "PUT";
            //设置超时时间
            httpWebRequest.Timeout = 20000;
            //将参数写入请求地址中
            httpWebRequest.GetRequestStream().Write(bs, 0, bs.Length);
            //请求头加入token
            httpWebRequest.Headers.Add("Authorization", token);
            //发送请求
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //读取返回数据
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
            string responseContent = streamReader.ReadToEnd();
            streamReader.Close();
            httpWebResponse.Close();
            httpWebRequest.Abort();
            return responseContent;
        }

        /// <summary>
        /// 发送DELETE请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="data">请求参数</param>
        /// <returns></returns>
        /// 
        public async Task<string> Delete(string url, string token)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            //设置请求类型
            httpWebRequest.Method = "DELETE";
            //设置超时时间
            httpWebRequest.Timeout = 20000;
            //发送请求
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //读取返回数据
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
            //请求头加入token
            httpWebRequest.Headers.Add("Authorization", token);
            string responseContent = streamReader.ReadToEnd();
            streamReader.Close();
            httpWebResponse.Close();
            httpWebRequest.Abort();
            return responseContent;
        }

        /// <summary>
        /// 发送DELETE请求（批量）
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="data">请求参数</param>
        /// <returns></returns>
        /// 
        public async Task<string> Delete(string url, string data, string token)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            //字符串转换为字节码
            byte[] bs = Encoding.UTF8.GetBytes(data);
            //参数类型，这里是json类型
            //还有别的类型如"application/x-www-form-urlencoded"
            httpWebRequest.ContentType = "application/json";
            //参数数据长度
            httpWebRequest.ContentLength = bs.Length;
            //设置请求类型
            httpWebRequest.Method = "DELETE";
            //设置超时时间
            httpWebRequest.Timeout = 20000;
            //将参数写入请求地址中
            httpWebRequest.GetRequestStream().Write(bs, 0, bs.Length);
            //请求头加入token
            httpWebRequest.Headers.Add("Authorization", token);
            //发送请求
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //读取返回数据
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
            string responseContent = streamReader.ReadToEnd();
            streamReader.Close();
            httpWebResponse.Close();
            httpWebRequest.Abort();
            return responseContent;
        }

        public async Task<string> HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        public async Task<string> Post(string url, Dictionary<string, string> content)
        {
            url = await _httpSender.FixUrl(url);
            Task<HttpResponseMessage> task = client.PostAsync(url, new FormUrlEncodedContent(content));
            try
            {
                return await _httpSender.RunTask(task);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public async Task<string> Put(string url)
        {
            url = await _httpSender.FixUrl(url);
            Task<HttpResponseMessage> task = client.PutAsync(url, null);
            try
            {
                return await _httpSender.RunTask(task);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public async Task<string> Put(string url, Dictionary<string, string> content)
        {
            url = await _httpSender.FixUrl(url);
            Task<HttpResponseMessage> task = client.PutAsync(url, new FormUrlEncodedContent(content));
            try
            {
                return await _httpSender.RunTask(task);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <returns></returns>
        public async Task<Stream> DownloadFile(string fileUrl)
        {
            var httpClientHandler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
            };
            HttpClient client = new HttpClient(httpClientHandler);
            //根据图片链接转成byte字节数组  
            var urlContents = await client.GetByteArrayAsync(fileUrl);
            return new MemoryStream(urlContents);
        }
    }
}
